<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
// 账号模型
use App\Models\Business\Business as BusinessModel;
// 商品模型
use App\Models\Product\Product as ProductModel;
// 购物车模型
use App\Models\Product\Cart as CartModel;
// 订单模型
use App\Models\Product\Order as OrderModel;
// 消费记录模型
use App\Models\Business\Record as RecordModel;
// 订单商品模型
use App\Models\Product\OrderProduct as OrderProductModel;
// 地址模型
use App\Models\Business\Address as AddressModel;
// 支付模型
use App\Models\Pay\Pay as PayModel;
// 退货订单
use App\Models\Depot\Back as BackModel;
// 退货订单商品
use App\Models\Depot\BackProduct as BackProductModel;
// 物流模型
use App\Models\Expressquery as ExpressqueryModel;
// 配置模型
use App\Models\Config as ConfigModel;
// 引入Validator 
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;



class Order extends Controller
{
    // 购物车下单
    public function add()
    {
        $busid = request('busid', 0);
        $cartid = request('cartid', 0);
        $amount = request('amount', 0);
        $remark = request('remark', '');
        $addressid = request('addressid', 0);
        $cartids = explode(',', $cartid);
        $businessinfo = BusinessModel::find($busid)->toArray();
        if (!$businessinfo) {
            return error('用户不存在');
        }

        $cartinfo = CartModel::whereIn('id', $cartids)->orderBy('proid', 'asc')->get()->toArray();
        $proids = CartModel::whereIn('id', $cartids)->pluck('proid')->toArray();
        $proinfo = ProductModel::whereIn('id', $proids)->get()->toArray();
        if (!$cartinfo) {
            return error('购物车商品不存在');
        };
        if (!$proinfo) {
            return error('商品不存在');
        }
        $addressinfo = AddressModel::find($addressid)->toArray();

        if (!$addressinfo) {
            return error('收货地址不存在');
        }

        // 判断库存
        foreach ($proinfo as $index => $item) {
            $stock = bcsub($item['stock'], $cartinfo[$index]['nums']);
            if ($stock < 0) {
                return error($item['name'] . '商品库存不足');
            }
        }

        // 判断余额
        $money = bcsub($businessinfo['money'], $amount, 2);

        if ($money < 0) {
            return error('余额不足,请去充值');
        }
        // 开启事务
        DB::beginTransaction();
        try {

            // 减少余额
            $BusinessStatus = BusinessModel::where('id', $busid)->update(['money' => $money]);
            if ($BusinessStatus === false) {
                return error('操作失败');
            }

            // 添加订单
            $orderData = [
                'code' => build_code('SP'),
                'busid' => $busid,
                'amount' => $amount,
                'remark' => $remark,
                'status' => '1',
                'consignee' => $addressinfo['consignee'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'address' => $addressinfo['address'],
                'mobile' => $addressinfo['mobile'],

            ];
            // 订单校验器
            $rule = [
                'busid'       => ['required'],
                'amount'      => ['required'],
                'status'      => ['required'],
                'consignee'   => ['required'],
                'code'        => ['required', 'unique:order'],
                'province'    => ['required'],
                'city'        => ['required'],
                'district'    => ['required'],
                'address'     => ['required'],
                'mobile'      => ['required', 'regex:/^1[3456789]{1}\d{9}$/']
            ];

            // 错误提示信息
            $message = [
                'amount.required'   => '订单金额必填',
                'code.unique'   => '订单号已经存在',
                'status.required'   => '订单状态必填',
                'consignee.required' => '收件人名字必填',
                'busid.required'    => '客户ID必填',
                'code.required'     => '订单号必填',
                'province.required' => '省必填',
                'city.required'     => '市必填',
                'district.required' => '区必填',
                'address.required'  => '详细地址必填',
                'mobile.required'   => '收件人手机必填',
                'mobile.regex' => '手机号格式错误'
            ];
            $validator = Validator::make($orderData, $rule, $message);

            if ($validator->fails()) {
                return error($validator->errors()->first());
            }
            // 添加订单
            $orderinfo = OrderModel::create($orderData);
            if (!$orderinfo) {
                return error('订单生成失败');
            }
            $recordData = [
                'busid' => $busid,
                'state' => '2',
                'content' => '在商城购买了',
                'total' => $amount
            ];
            // 订单产品表数据
            $OrderProData = [];
            // 产品表数据
            $ProductData = [];

            // 减少库存
            foreach ($proinfo as $index => $item) {
                $data = [
                    'orderid' => $orderinfo['id'],
                    'proid' => $cartinfo[$index]['proid'],
                    'pronum' => $cartinfo[$index]['nums'],
                    'price' => $cartinfo[$index]['price'],
                    'total' => $cartinfo[$index]['total'],
                    'busid' => $busid
                ];
                $recordData['content'] .= '[' . $item['name'] . ']商品' . $cartinfo[$index]['nums'] . '件、';
                // 订单商品表校验器
                $rule1 = [
                    'orderid' => ['required'],
                    'proid' => ['required'],
                    'pronum' => ['required'],
                    'price' => ['required'],
                    'total' => ['required'],
                    'busid' => ['required']
                ];

                // 错误提示信息
                $message1 = [
                    'orderid.required' => '订单id必填',
                    'proid.required' => '商品id必填',
                    'total.required' => '订单商品总计必填',
                    'pronum.required' => '商品数量必填',
                    'price.required' => '订单商品单价必填',
                    'busid.required' => '用户id必填',
                ];

                // 校验器
                $validator1 = Validator::make($data, $rule1, $message1);
                if ($validator1->fails()) {
                    return error($validator1->errors()->first());
                }

                $stock = bcsub($item['stock'], $cartinfo[$index]['nums']);

                $OrderProData[] = $data;

                $ProductData[] = [
                    'id' => $item['id'],
                    'stock' => $stock
                ];
            }

            // 添加订单商品表
            $OrderProStatus = OrderProductModel::insert($OrderProData);

            if (!$OrderProStatus) {
                return error('操作失败');
            }
            $recordData['content'] = rtrim($recordData['content'], '、');

            $recordData['content'] .= "，花费了" . $orderinfo['amount'] . "元";
            // 消费记录校验器
            $rule2 = [
                'total' => ['required'],
                'content' => ['required'],
                'busid' => ['required'],
                'state' => ['required']
            ];

            // 错误提示信息
            $message2 = [
                'total.required' => '消费金额必填',
                'content.required' => '消费描述必填',
                'busid.required' => '用户id必填',
                'state.required' => '状态消费积分必填',
            ];
            // 校验器
            $validator2 = Validator::make($recordData, $rule2, $message2);
            if ($validator2->fails()) {
                return error($validator2->errors()->first());
            }
            // 添加消费记录
            $RecordStatus = RecordModel::create($recordData);
            if (!$RecordStatus) {
                return error('操作失败');
            }
            // 删除购物车
            CartModel::whereIn('id', $cartids)->delete();

            // 商品表库存： 批量更新
            $ProductStatsu = $this->updateBatch('pre_product', $ProductData);
            if ($ProductStatsu === false) {
                return error('操作失败');
            }
            DB::commit();
            return success('下单成功');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('下单失败');
        }
    }
    // 列表
    public function index()
    {
        $busid = request('busid', 0);
        $status = request('status', '');
        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $dp = OrderModel::query();

        if (!empty($status) ||  $status == '0') {
            if ($status == '-1') {
                $dp->whereIn('status', ['-1', '-2', '-3']);
            } else if ($status == '-4') {
                $dp->whereIn('status', ['-4', '-5']);
            } else {
                // 批量查询ID值
                $dp->whereIn('status', [$status]);
            }
        }

        $data = $dp->where('busid', $busid)->orderBy('createtime', 'desc')->get();

        foreach ($data as $item) {
            $product = OrderProductModel::with('product')->where('orderid', $item['id'])->first();

            $item['info'] = $product;
        }

        return success('', $data);
    }
    // 创建商品订单
    public function buy()
    {
        $busid = request('busid', 0);
        $amount = request('amount', 0);
        $remark = request('remark', '');
        $addressid = request('addressid', 0);
        $proid = request('proid', 0);
        $businessinfo = BusinessModel::find($busid)->toArray();
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $proinfo = ProductModel::find($proid)->toArray();
        if (!$proinfo) {
            return error('商品不存在');
        }
        $stock = bcsub($proinfo['stock'], 1);
        if ($stock < 0) {
            return error($proinfo['name'] . '商品库存不足');
        }
        $addressinfo = AddressModel::find($addressid)->toArray();

        if (!$addressinfo) {
            return error('收货地址不存在');
        }

        // 开启事务
        DB::beginTransaction();
        try {
            // 添加订单
            $orderData = [
                'code' => build_code('SP'),
                'busid' => $busid,
                'amount' => $amount,
                'remark' => $remark,
                'status' => '0',
                'consignee' => $addressinfo['consignee'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'address' => $addressinfo['address'],
                'mobile' => $addressinfo['mobile'],

            ];
            // 订单校验器
            $rule = [
                'busid'       => ['required'],
                'amount'      => ['required'],
                'status'      => ['required'],
                'consignee'   => ['required'],
                'code'        => ['required', 'unique:order'],
                'province'    => ['required'],
                'city'        => ['required'],
                'district'    => ['required'],
                'address'     => ['required'],
                'mobile'      => ['required', 'regex:/^1[3456789]{1}\d{9}$/']
            ];

            // 错误提示信息
            $message = [
                'amount.required'   => '订单金额必填',
                'code.unique'   => '订单号已经存在',
                'status.required'   => '订单状态必填',
                'consignee.required' => '收件人名字必填',
                'busid.required'    => '客户ID必填',
                'code.required'     => '订单号必填',
                'province.required' => '省必填',
                'city.required'     => '市必填',
                'district.required' => '区必填',
                'address.required'  => '详细地址必填',
                'mobile.required'   => '收件人手机必填',
                'mobile.regex' => '手机号格式错误'
            ];
            $validator = Validator::make($orderData, $rule, $message);

            if ($validator->fails()) {
                return error($validator->errors()->first());
            }
            // 添加订单
            $orderinfo = OrderModel::create($orderData);
            if (!$orderinfo) {
                return error('订单生成失败');
            }
            // 订单产品表数据
            $OrderProData = [
                'orderid' => $orderinfo->id,
                'proid' => $proinfo['id'],
                'pronum' => 1,
                'price' => $proinfo['price'],
                'total' => $proinfo['price'],
                'busid' => $busid
            ];

            // 订单商品表校验器
            $rule1 = [
                'orderid' => ['required'],
                'proid' => ['required'],
                'pronum' => ['required'],
                'price' => ['required'],
                'total' => ['required'],
                'busid' => ['required']
            ];

            // 错误提示信息
            $message1 = [
                'orderid.required' => '订单id必填',
                'proid.required' => '商品id必填',
                'total.required' => '订单商品总计必填',
                'pronum.required' => '商品数量必填',
                'price.required' => '订单商品单价必填',
                'busid.required' => '用户id必填',
            ];

            // 校验器
            $validator1 = Validator::make($OrderProData, $rule1, $message1);
            if ($validator1->fails()) {
                return error($validator1->errors()->first());
            }

            // 添加订单商品
            $OrderProStatus = OrderProductModel::create($OrderProData);

            if (!$OrderProStatus) {
                return error('订单商品生成失败');
            }
            // 减少商品表库存
            $ProductStatsu = ProductModel::where('id', $proid)->update(['stock' => $stock]);
            if ($ProductStatsu === false) {
                return error('操作失败');
            }
            DB::commit();
            return success("下单成功", $orderinfo->id);
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('下单失败');
        }
    }
    // 支付
    public function payment()
    {
        $orderid = request('orderid', 0);
        $busid = request('busid', 0);
        $way = request('way', 2);
        $businessinfo = BusinessModel::find($busid)->toArray();
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $orderinfo = OrderModel::find($orderid);
        if (!$orderinfo) {
            return error('订单不存在');
        }
        // 开启事务
        DB::beginTransaction();
        try {
            $orderProinfo = OrderProductModel::with('product')->firstWhere('orderid', $orderid);
            if ($way == 2) {

                $amount = $orderinfo->amount;
                // 判断余额
                $money = bcsub($businessinfo['money'], $amount, 2);
                if ($money < 0) {
                    return error('余额不足,请去充值');
                }
                // 修改订单状态
                OrderModel::where('id', $orderid)->update(['status' => '1']);
                // 减少余额

                $BusinessStatus = BusinessModel::where('id', $busid)->update(['money' => $money]);
                if ($BusinessStatus === false) {
                    return error('操作失败');
                }
                $recordData = [
                    'busid' => $busid,
                    'state' => '2',
                    'content' => '在商城购买了[' . $orderProinfo['product']['name'] . ']商品' . $orderProinfo['pronum'] . '件，花费了' . $orderProinfo['price'] . '元',
                    'total' => $amount
                ];
                // 消费记录校验器
                $rule2 = [
                    'total' => ['required'],
                    'content' => ['required'],
                    'busid' => ['required'],
                    'state' => ['required']
                ];

                // 错误提示信息
                $message2 = [
                    'total.required' => '消费金额必填',
                    'content.required' => '消费描述必填',
                    'busid.required' => '用户id必填',
                    'state.required' => '状态消费积分必填',
                ];
                // 校验器
                $validator2 = Validator::make($recordData, $rule2, $message2);
                if ($validator2->fails()) {
                    return error($validator2->errors()->first());
                }
                // 添加消费记录
                $RecordStatus = RecordModel::create($recordData);
                if (!$RecordStatus) {
                    return error('操作失败');
                }
                DB::commit();
                return success('支付成功');
            } else {
                $money = floatval($orderinfo['amount']);

                if ($money < 0) {
                    $this->error('订单金额不能小于1元');
                }
                // 用户ID
                $third = json_encode(['busid' => $busid, 'orderid' => $orderid]);

                // Env 获取env文件路面的，没有再获取数据库里的 获取当前站点域名
                $urls = ConfigModel::where('name', 'url')->value('value');
                $url = env('SITES_URL', $urls);
                $wxcode = $url . ConfigModel::where('name', 'wxcode')->value('value');
                $zfbcode = $url . ConfigModel::where('name', 'zfbcode')->value('value');
                // 下单地址
                $OrderUrl = $url . '/pay/index/create';

                $data = [
                    'name' => $orderProinfo['product']['name'] . '商品购买',
                    'third' => $third,
                    'paytype' => $way,
                    'originalprice' => $money,
                    'paypage' => 0, // 0 json 1 收银页面,
                    'reurl' => 'http://jie.laravelshop.jied.top/shop/order/notice',
                    'callbackurl' => 'http://jie.laravelshop.jied.top/shop/order/callback',
                    'status' => '0',
                    'wxcode' => $wxcode,
                    'zfbcode' => $zfbcode,
                ];
                $result = httpRequest($OrderUrl, $data, 1);
                echo $result;
                exit;
            }
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('支付失败');
        }
    }
    // 根据id查询支付订单
    public function pay()
    {
        $id = request('id', 0);
        $result = PayModel::find($id);
        if ($result) {
            return success('查询成功', $result);
        }
        return error('支付订单不存在');
    }
    // 购买课程成功回调函数
    public function callback()
    {

        $params = request()->all();
        $price = isset($params['price']) ? $params['price'] : 0;

        $third = isset($params['third']) ? $params['third'] : '';
        // json字符串($third,true) true 转换数组 默认对象
        if($third){
            $third = json_decode($third, true);
        }
        $orderid = isset($third['orderid']) ? $third['orderid'] : 0;
        $busid = isset($third['busid']) ? $third['busid'] : 0;
        $paytype = isset($params['paytype']) ? $params['paytype'] : 0;
        // 支付订单id
        $payid = isset($params['id']) ? $params['id'] : 0;
        $pay = PayModel::find($payid);

        if (!$pay) {
            return error('购买订单不存在');
        }
        // 充值类型转换
        $payment = '';
        switch ($paytype) {
            case 0:
                $payment = "微信支付";
                break;
            case 1:
                $payment = "支付宝支付";
                break;
        }

        // 判断充值金额
        if ($price <= 0) {
            return error("购买商品金额为0");
        }
        // 开启事务
        DB::beginTransaction();
        try {
            $orderProinfo = OrderProductModel::with('product')->firstWhere('orderid', $orderid);
            $orderinfo = OrderModel::find($orderid);
            if (!$orderinfo) {
                return error('订单不存在');
            }
            // 修改订单状态
            OrderModel::where('id', $orderid)->update(['status' => '1']);
            $recordData = [
                'busid' => $busid,
                'state' => '2',
                'content' => '在商城使用'. $payment.'购买了[' . $orderProinfo['product']['name'] . ']商品' . $orderProinfo['pronum'] . '件，花费了' . $orderProinfo['price'] . '元',
                'total' => $orderinfo['amount']
            ];
            // 消费记录校验器
            $rule2 = [
                'total' => ['required'],
                'content' => ['required'],
                'busid' => ['required'],
                'state' => ['required']
            ];

            // 错误提示信息
            $message2 = [
                'total.required' => '消费金额必填',
                'content.required' => '消费描述必填',
                'busid.required' => '用户id必填',
                'state.required' => '状态消费积分必填',
            ];
            // 校验器
            $validator2 = Validator::make($recordData, $rule2, $message2);
            if ($validator2->fails()) {
                return error($validator2->errors()->first());
            }
            // 添加消费记录
            RecordModel::create($recordData);
            DB::commit();
            return success('支付成功');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('支付失败');
        }
    }
    //  购买课程完成后跳转的网页
    public function notice()
    {
        return success('购买商品成功', '/business/order/index');
    }

    // 详情
    public function info()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $orderproid = request('orderproid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $where = [];
        $where['orderid'] = $orderid;

        // 评价页面查询商品
        if ($orderproid > 0) {
            $where['id'] = $orderproid;
        }

        $proinfo = OrderProductModel::with('product')->where($where)->get();

        $orderinfo['proinfo'] = $proinfo;
        // 判断是否有物流信息
        if ($orderinfo['expresscode']) {
            if (cache()->get($orderinfo['expresscode'])) {
                $express = cache($orderinfo['expresscode']);
                $orderinfo['express'] = $express;
            } else {
                $res = query_express($orderinfo['expresscode']);

                if ($res['result'] == false) {
                    
                    return error($res['msg']);
                }
                cache()->put($orderinfo['expresscode'], $res['data']);
                $orderinfo['express'] = $res['data'];
            }
        }
        if ($orderinfo['status'] == '-2' || $orderinfo['status'] == '-3') {
            $telephone = ConfigModel::where('name', 'telephone')->value('value');
            $address = ConfigModel::where('name', 'address')->value('value');
            $manufacturer = [
                'telephone' => $telephone,
                'address' => $address
            ];
            $orderinfo['manufacturer'] = $manufacturer;
            if ($orderinfo['status'] == '-3') {
                $back = BackModel::where('ordercode', $orderinfo['code'])->first();
                $orderinfo['back'] = $back;
                if (isset($back['expresscode'])) {
                    if (cache()->get($back['expresscode'])) {
                        $express = cache($back['expresscode']);
                        $orderinfo['back']['express'] = $express;
                    } else {
                        $res = query_express($back['expresscode']);
                        if ($res['result'] == false) {
                            return error($res['msg']);
                        }
                        cache()->put($back['expresscode'], $res['data']);
                        $orderinfo['back']['express'] = $res['data'];
                    }
                }
            }
        }
        return success('', $orderinfo);
    }

    // 确认收货
    public function confirm()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $result = OrderModel::where('id', $orderid)->update(['status' => '3']);

        if ($result === false) {
            return error('确认收货失败');
        } else {
            return success('确认收货成功');
        }
    }

    // 商品评价
    public function rate()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $orderproid = request('orderproid', 0);
        $rate = request('rate', null);
        $comment = request('comment', null);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $orderproductlist = OrderProductModel::where('orderid', $orderid)->get();

        if (!$orderproductlist) {
            return error('订单商品不存在');
        }
        //判断是否订单商品最后一个评价
        $comment_status = true;
        foreach ($orderproductlist as $item) {
            // 判断未评价，并且评价商品不是当前商品
            if (!$item['rate'] && $item['id'] != $orderproid) {
                $comment_status = false;
            }
        }
        // 开启事务
        DB::beginTransaction();

        try {
            if ($comment_status) {
                $OrdreStatus = OrderModel::where('id', $orderid)->update(['status' => '4']);
            }
            if (!$comment_status || $OrdreStatus) {
                $orderProData = [
                    'rate' => $rate,
                    'comment' => $comment,
                    'busid' => $busid
                ];
                $proimgs = request()->file('proimg');
                if ($proimgs) {
                    $res = updloads($proimgs);
                    if ($res['code'] == 0) {
                        return error($res['msg']);
                    }
                    $orderProData['proimg'] = $res['data'];
                }
                OrderProductModel::where('id', $orderproid)->update($orderProData);
                DB::commit();
                return success('评价成功');
            }
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('评价失败');
        }
    }
    // 退货
    public function refund()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $status = request('status', '');
        $refundreason = request('refundreason', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $result = OrderModel::where('id', $orderid)->update(['status' => $status, 'refundreason' => $refundreason]);

        if ($result) {
            return success('申请退货成功，待审核');
        } else {
            return error('申请退货失败');
        }
    }


    // 商品退货物流公司和快递地址列表
    public function expresslist()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $address = AddressModel::where('busid', $busid)->get();

        $addresslist = [];

        foreach ($address as $item) {
            $addresslist[] = [
                'text' => $item['consignee'] . '-' . $item['mobile'] . '-' . $item['address_text'] . $item['address'],
                'value' => $item['id']
            ];
        }

        $expresslist = ExpressqueryModel::select('id as value', 'name as text')->get();

        $data = [
            'addresslist' => $addresslist,
            'expresslist' => $expresslist
        ];

        return success('', $data);
    }

    // 商品退货
    public function refundgoods()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $expresscode = request('expresscode', '');
        $expressid = request('expressid', 0);
        $addressid = request('addressid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $orderproductlist = OrderProductModel::where('orderid', $orderid)->get();

        if (!$orderproductlist) {
            return error('订单商品不存在');
        }

        $addressinfo = AddressModel::find($addressid);

        if (!$addressinfo) {
            return error('地址不存在');
        }

        $expressinfo = ExpressqueryModel::find($expressid);

        if (!$expressinfo) {
            return error('物流公司不存在');
        }

        // 开启事务
        DB::beginTransaction();

        try {

            $BackData = [
                'ordercode' => $orderinfo['code'],
                'code' => build_code('BP'),
                'busid' => $busid,
                'contact' => $addressinfo['consignee'],
                'phone' => $addressinfo['mobile'],
                'address' => $addressinfo['address'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'amount' => $orderinfo['amount'],
                'expressid' => $expressid,
                'expresscode' => $expresscode,
                'status'=>'1'
            ];

            $BackStatus = BackModel::create($BackData);

            if ($BackStatus === false) {
                return error('操作失败');
            }


            $BackProData = [];

            foreach ($orderproductlist as $item) {
                $BackProData[] = [
                    'backid' => $BackStatus->id,
                    'proid' => $item['proid'],
                    'nums' => $item['pronum'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $BackProStatus = BackProductModel::insert($BackProData);

            if ($BackProStatus === false) {
                return error('操作失败');
            }

            DB::commit();
            return success('提交成功，待审核');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('退货失败');
        }
    }




    // 批量更新多条数据方法
    public function updateBatch($tableName = "", $multipleData = array())
    {
        if ($tableName && !empty($multipleData)) {

            // column or fields to update  
            $updateColumn = array_keys($multipleData[0]);

            $referenceColumn = $updateColumn[0]; //e.g id

            $whereIn = "";

            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .=  $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" .  rtrim($whereIn, ', ') . ")";
            // Update    
            return DB::update(DB::raw($q));
        } else {
            return false;
        }
    }
}
